//
//  RadioView.swift
//  xgwjinterconnection
//  收音机页面
//  Created by WangWeiShuo on 2025/8/19.
//

import SwiftUI
import Combine

struct RadioView: View {
    @Environment(\.dismiss) var dismiss
    
    @StateObject private var socketManager = SocketManager.shared
    @State private var cancellables = Set<AnyCancellable>()
    // 用于存储定时器订阅
    @State private var cancellable: AnyCancellable?
    // 控制定时器状态
    @State private var isRunning: Bool = false
    //是否静音
    @State private var isMute: Bool = false
    @State private var volumeValue: Float = 50 // 音量初始值
    @State private var beforeMuteVolume: Double = 0
    @State private var currentLoveRadio = 0
    
    @State private var collectRadio = ["0","0","0","0","0","0"]
    @State private var selectedTab = 0
    @State private var radioOpen = 0
    
    @State private var radioInfo: RadioInfoBean?
    
    var body: some View {
        VStack(){
            WikaNavigationView(showBackIcon: true, title: NSLocalizedString("radio_title", comment: "收音机"),onBack: {
                dismiss() }).frame(maxHeight: 65)
            
            HStack(){
                Spacer()
                ToggleIconButton(iconNormal: "icon_volume_normal",iconPressed: "icon_volume_mute",isPressed: isMute ? true : false){
//                    isMute.toggle()
                    
                    if(isMute){
                        isMute = false
//                        beforeMuteVolume = volumeValue
//                        volumeValue = 0
                    }else{
                        isMute = true
//                        volumeValue = beforeMuteVolume
                    }
                    SendMsgUtils.sendControlMessage(socket: socketManager, type: SendMessageType.SEND_MSG_RADIO_MUTE,value: isMute ? 1 : 0)
                }
                
                Divider()
                    .frame(height: 40)
                    .padding(.vertical, 5)
                
                Slider(value: $volumeValue, in: 0...100)
                    .onChange(of: volumeValue) { newValue in
                        print("值变为: \(newValue)")
                        // 执行额外操作，如更新UI、网络请求等
                        SendMsgUtils.sendControlMessage(socket: socketManager, type: SendMessageType.SEND_MSG_RADIO_VOLUME,value: UInt8(newValue))
                    }
                //                    CustomSlider(value: $volumeValue, in: 0...100, trackHeight: 20)
            }
            .padding()
            .background(Color("color_gray_f3f3f3"))
            .frame(width:.infinity,height: 70)
            .cornerRadius(10)
            .padding(.top,-25)
            .padding(.horizontal)
            
            SegmentTextView(options: collectRadio, selectedIndex: $currentLoveRadio,height: 70).frame(height: 70)
                .padding()
                .onChange(of: currentLoveRadio) { newValue in
                    SendMsgUtils.sendControlMessage(socket: socketManager, type: SendMessageType.SEND_MSG_RADIO_COLLECT,value: UInt8(newValue))
                }
            
            HStack(){
                Button {
                    // 温度减按钮点击事件
                    print("切换上一台")
                    SendMsgUtils.sendControlMessage(socket: socketManager, type: SendMessageType.SEND_MSG_RADIO_PROGRAM,value:2)
                } label: {
                    Image("icon_pre_normal")
                        .resizable()
                        .scaledToFit()
                        .font(.largeTitle) // 控制图标大小
                        .foregroundColor(.gray) // 图标颜色
                }
                
                Spacer()
                
                Button{
                    print("APS")
                    SendMsgUtils.sendControlMessage(socket: socketManager, type: SendMessageType.SEND_MSG_RADIO_PROGRAM,value:0)
                }label: {
                    Text("APS").font(.largeTitle)
                        .foregroundColor(.black)
                }
                
                Spacer()
                
                Button {
                    // 温度加按钮点击事件
                    print("切换下一台")
                    SendMsgUtils.sendControlMessage(socket: socketManager, type: SendMessageType.SEND_MSG_RADIO_PROGRAM,value:1)
                } label: {
                    Image("icon_next_normal")
                        .resizable()
                        .scaledToFit()
                        .foregroundColor(.gray) // 图标颜色
                }
            }
            .padding()
            .background(Color("color_gray_f3f3f3"))
            .frame(width:.infinity,height: 70)
            .cornerRadius(10)
            .padding(.horizontal)
            
            CustomSegmentedControl(options: ["FM", "AM"], selectedIndex: $selectedTab,height: 50).frame(height: 70)
                .padding()
                .onChange(of: selectedTab) { newValue in
                    SendMsgUtils.sendControlMessage(socket: socketManager, type: SendMessageType.SEND_MSG_RADIO_MODE,value:UInt8(newValue))
                }
            
            Spacer()
            
            HStack(){
                Text(String(radioInfo?.currentradio ?? 66)).font(.largeTitle)
                Text(selectedTab == 0 ? "MHz" : "KHz").font(.largeTitle).foregroundColor(Color.gray)
            }
            
            Spacer()
            
            ToggleIconButton(iconNormal: "icon_switch_normal",iconPressed: "icon_switch_pressed",isPressed: radioOpen == 1 ? true : false){
                SendMsgUtils.sendControlMessage(socket: socketManager, type: SendMessageType.SEND_MSG_RADIO_MODE,value:radioOpen == 0 ? 1 : 0)
            }.frame(width: 70)
            
            Spacer()
        }
        .navigationTitle("")
        .navigationBarHidden(true)
        .enableSwipeBackGesture()
        .onAppear {
            // 订阅用户信息消息
            socketManager.subscribeToRadioInfo()
                .receive(on: DispatchQueue.main)
                .sink {  info in
                    radioInfo = info
                    print("当前音量11111：\(radioInfo?.radiovolume)")
                    self.volumeValue = Float(radioInfo?.radiovolume ?? 0) ??  self.volumeValue
                    self.isMute = radioInfo?.voicemutex == 1 ? true : false
                    let isFm = radioInfo?.radiomode == 0 ? true : false
                    self.selectedTab = isFm ? 0 : 1
                    self.radioOpen = Int(radioInfo?.switchon ?? 0) ?? self.radioOpen
                    print("当前音量：\(volumeValue)")
                    print("是否静音：\(isMute)")
                    let collect = radioInfo?.collectradio
                    if(((collect?.isEmpty) == nil)){
                        self.collectRadio = collect?.components(separatedBy: ",") ?? self.collectRadio
                    }
                }
                .store(in: &cancellables)
            SendMsgUtils.sendGetMessage(socket: socketManager,type: SendMessageType.GET_MSG_RADIO_INFO)
            startTimer()
        }
        .onDisappear{
            stopTimer()
        }
    }
    
    // 启动定时器
    private func startTimer() {
        isRunning = true
        // 创建定时器：每隔1秒发送一次信号，在主线程接收
        cancellable = Timer.publish(every: 5, on: .main, in: .common)
            .autoconnect()
            .sink { _ in
                // 每秒执行的任务
                print("定时器执行")
                SendMsgUtils.sendGetMessage(socket: socketManager,type: SendMessageType.GET_MSG_RADIO_INFO)
            }
    }
    
    // 停止定时器
    private func stopTimer() {
        isRunning = false
        cancellable?.cancel() // 取消订阅
        cancellable = nil
    
    }
    
}

#Preview {
    RadioView()
}


